import { useNavigate, Link } from "react-router-dom";
import React, { useState, useEffect } from "react";
import { Card, Button, Checkbox, Form, Input, message } from "antd";
import { captcha } from "../../api/user_api";
import userLoginStore from "../../store/userLoginStore";

const Login = () => {
  const navigate = useNavigate();
  const { login } = userLoginStore();
  const [captchaSvg, setCaptchaSvg] = useState("");

  useEffect(() => {
    getCaptcha();
  }, []);

  const getCaptcha = () => {
    captcha().then((res) => {
      setCaptchaSvg(res.data);
    });
  };
  const onFinish = async (values) => {
    try {
      await login(values);
      navigate("/home");
    } catch (error) {
      message.error(error.msg);
    }
  };

  return (
    <div
      style={{
        height: 800,
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <Card
        style={{
          width: 400,
        }}
        title="登录"
        styles={{
          title: {
            textAlign: "center",
          },
        }}
      >
        <Form
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="账号"
            name="username"
            rules={[
              {
                required: true,
                message: "用户账号不能为空!",
              },
            ]}
          >
            <Input placeholder="请输入账号" />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入密码!",
              },
            ]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
            label="验证码"
            name="captcha"
            rules={[
              {
                required: true,
                message: "请输入验证码!",
              },
            ]}
          >
            <div style={{ display: "flex" }}>
              <Input placeholder="请输入验证码" style={{ flex: 1 }} />
              <div
                onClick={getCaptcha}
                style={{ cursor: "pointer", marginLeft: 10 }}
                dangerouslySetInnerHTML={{ __html: captchaSvg }}
              ></div>
            </div>
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked" label={null}>
            <Checkbox>Remember me</Checkbox>
          </Form.Item>

          <Form.Item style={{ textAlign: "center" }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};
export default Login;
